<?php
// 循环创建目录
function mk_dir($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode))
        return true;
    if (!mk_dir(dirname($dir), $mode))
        return false;
    return @mkdir($dir, $mode);
}
function get_atype($type){
    if($type==1){
        return "A&nbsp;(9:1)";
    }elseif($type==2){
        return "B&nbsp;(8:2)";
    }else{
        return "C&nbsp;(7:3)";
    }
}
function message($phone){
    $num=rand(1,9).rand(1,9).rand(1,9).rand(1,9).rand(1,9).rand(1,9);
    $code=urlencode("#code#=".$num);
    $appKey="3a2a10af059217d152056fca145b7dbc";
    $url="http://v.juhe.cn/sms/send?mobile=".$phone."&tpl_id=37869&tpl_value=".$code."&key=".$appKey;
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);curl_setopt ($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_exec($ch);
    curl_close($ch);
    return $num;
}



/*
 * 状态修改*/
function get_status($type){
    if($type==0){
        return "<span class='label label-warning radius'>未审核</span>";
    }elseif($type==1){
        return "<span class='label label-success radius'>已通过</span>";
    }else{
        return "<span class='label label-danger radius'>未通过</span>";
    }
}

//加密函数
function encrypt($txt, $key = null)
{
    if (empty($key)) {
        $key = C('SECURE_CODE');
    }
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=+";
    $nh = rand(0, 64);
    $ch = $chars [$nh];
    $mdKey = md5($key . $ch);
    $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
    $txt = base64_encode($txt);
    $tmp = '';
    $i = 0;
    $j = 0;
    $k = 0;
    for ($i = 0; $i < strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = ($nh + strpos($chars, $txt [$i]) + ord($mdKey [$k++])) % 64;
        $tmp .= $chars [$j];
    }
    return $ch . $tmp;
}

//解密函数
function decrypt($txt, $key = null)
{
    if (empty($key)) {
        $key = C('SECURE_CODE');
    }
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=+";
    $ch = $txt [0];
    $nh = strpos($chars, $ch);
    $mdKey = md5($key . $ch);
    $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
    $txt = substr($txt, 1);
    $tmp = '';
    $i = 0;
    $j = 0;
    $k = 0;
    for ($i = 0; $i < strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = strpos($chars, $txt [$i]) - $nh - ord($mdKey [$k++]);
        while ($j < 0)
            $j += 64;
        $tmp .= $chars [$j];
    }
    return base64_decode($tmp);
}

/**
 * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 * @return string
 */
function rand_string($len = 6, $type = '', $addChars = '')
{
    $str = '';
    switch ($type) {
        case 0:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        case 1:
            $chars = str_repeat('0123456789', 3);
            break;
        case 2:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
            break;
        case 3:
            $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        default :
            // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
            break;
    }
    if ($len > 10) { //位数过长重复字符串一定次数
        $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
    }
    if ($type != 4) {
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
    } else {
        // 中文随机字
        for ($i = 0; $i < $len; $i++) {
            $str .= msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1);
        }
    }
    return $str;
}

/**
 * 获取登陆用户ID
 * @param string $str
 * @return number
 * @author Ice <iceinto@163.com>
 */
function getLoginUid($str = '')
{
    return intval($_SESSION[C('USER_AUTH_KEY') . $str]);
}

/**
 * 在活动中，获取当前活动编号
 */
function getActId()
{
    return intval($_SESSION['activityId']);
}
/**
 * 在活动中，获取当前用户的openid
 */
function getOpenid()
{
    return $_SESSION['openid'];
}

/**
 * 获取客户登陆id
 */
function getComLoginUid($str = '')
{
    return intval($_SESSION[C('USER_COM_AUTH_KEY') . $str]);
}

/**
 * 设置登陆用户ID
 * @param int $uid
 * @param string $str
 * @author Ice <iceinto@163.com>
 */
function setLoginUid($uid, $str = '')
{
    $_SESSION[C('USER_AUTH_KEY') . $str] = $uid;
}

/**
 * 设置客户登陆id
 */
function setComLoginUid($uid, $str = '')
{
    $_SESSION[C('USER_COM_AUTH_KEY') . $str] = $uid;
}

/**
 * 时间格式化
 * @param $time
 * @param string $fromat
 * @return bool|string
 */
function timeToDate($time, $fromat = 'Y-m-d')
{
    if (!empty($time)) {
        return date($fromat, $time);
    }
}

/**
 * 获取基础的URL
 * @return string
 */
function getBaseUrl()
{
    //return $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://' . $_SERVER['HTTP_HOST'] . (strpos($_SERVER['HTTP_HOST'], ':') === false ? $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT'] : '');
    return $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://' . $_SERVER['HTTP_HOST'];
}

/**
 * 状态说明
 * @param $status
 * @return mixed
 */
function statusInfo($status)
{
    $statusInfo = array();
    $statusInfo[0] = '不可用';
    $statusInfo[1] = '可用';
    $statusInfo[99] = '作废';
    $statusInfo[99] = '过期';
    $statusInfo[100] = '完成';
    return $statusInfo[$status];
}

/**
 * 格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author ice <iceinto@163.com>
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * Logic 简单调用
 * @param $name 名称
 * @return mixed
 */
function LD($name)
{
    return D($name, 'Logic');
}

/**
 * Service 简单调用
 * @param $name
 * @return mixed
 */
function SD($name)
{
    return D($name, 'Service');
}

/**
 * 设置跳转页面URL
 * 使用函数再次封装，方便以后选择不同的存储方式（目前使用cookie存储）
 * @author iceinto
 */
function setRedirectUrl($url)
{
    cookie('redirect_url', $url);
}

/**
 * 获取跳转页面URL
 * @return string 跳转页URL
 * @author iceinto
 */
function getRedirectUrl()
{
    $url = cookie('redirect_url');
    return empty($url) ? __APP__ : $url;
}

/**
 * 把对象转换成数组
 * @param   object $object 要转换的对象
 * @return  array
 */
function objectToArray($object)
{
    if (count($object) == 0) return trim((string)$object);
    $result = array();
    $object = is_object($object) ? get_object_vars($object) : $object;
    foreach ($object as $key => $val) {
        $val = (is_object($val) || is_array($val)) ? objectToArray($val) : $val;
        $result[$key] = $val;
    }
    return $result;
}

/**
 * 短信发送
 * @example $users = array(1=>13305148882,2=>15805168478); $body = '用户短信内容';
 * @param array $users 用户和号码数组
 * @param string $body 短信内容
 * @return bool
 * @author ice <iceinto@mallog.com.cn>
 */
function smsSend($users, $body)
{
    $status = false;
    if (is_array($users) && $body) {
        import('@.ORG.Net.Sms'); // 导入分页类
        $result = SMS::sendSMS($users, $body . '【和善园】');
        if ($result) {
            $SmsModel = M('Sms');
            $data = array();
            foreach ($users as $phone) {
                unset($data);
                $data['phone'] = $phone;
                $data['createtime'] = time();
                $data['content'] = $body;
                $data['word'] = strlen($body);
                $SmsModel->add($data);
            }
            $status = true;
        } else {
            Log::write('短信发送失败：' . serialize($users) . serialize($body));
        }
    }
    return $status;
}

/**
 * 找不同模板前台调用方法
 */
function get_game($gongge = "", $k = "")
{
    $rand = rand(1, $gongge);
    $list = "";
    $model = M("FindGameset");
    $map=array();
    $map['id']=getActId();
    $setinfo = $model->where($map)->find();
    for ($i = 1; $i <= $gongge; $i++) {

        if ($gongge == 9) {
            $ck = "style='float: left !important;margin: 0 5px !important;width: 29% !important;'";
        } elseif ($gongge == 16) {
            $ck = "style='float: left !important;margin: 0 5px !important;width: 21% !important;'";
        } elseif ($gongge == 25) {
            $ck = "style='float: left !important;margin: 0 5px !important;width: 16% !important;'";
        } elseif ($gongge == 36) {
            $ck = "style='float: left !important;margin: 0 4px !important;width: 13% !important;'";
        } elseif ($gongge == 49) {
            $ck = "style='float: left !important;margin: 0 6px !important;width: 10% !important;'";
        }
        if ($i == $rand) {
            $list .= "<li " . $ck . "  class=\"list_" . $k . "\"><img src=\"__UPLOAD__/bg/" . $setinfo["gamediffimg"] . "\"></li>";
        } else {
            $list .= "<li " . $ck . " ><img src=\"__UPLOAD__/bg/" . $setinfo["gamesameimg"] . "\"></li>";
        }
    }

    return $list;


}

    //  获取后台二级菜单
    // public function get_second_level_menu($first_level_id){
        // $second_menu = M('')->
    // }
